const http = require("http");
const mongoose = require("mongoose");
const Router = require("router");
const template = require("art-template");
const path = require("path");
const dateFormat = require("dateformat");
const serveStatic = require("serve-static");
const querystring = require("querystring");
const url = require("url");
//连接数据库
mongoose.connect("mongodb://localhost/playground", {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log("数据库连接成功!");
}).catch((err) => {
    console.log(err, "数据库连接失败!");
})
//创建Collection规则
const schema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: [2, "最小值不能小于2个字符!"],
        maxlength: [100, "最大值不能超过100个字符!"]
    },
    age: {
        type: Number,
        min: [5, "年龄不能低于5"],
        max: [120, "年龄不能超过120"]
    },
    sex: String,
    email: String,
    hobbies: [String],
    collage: String,
    enterDate: {
        type: Date,
        default: new Date()
    }
})
//创建Document Myinfo表
const myInfo = mongoose.model("Myinfo", schema);

//配置模板引擎的根路径
template.defaults.root = path.join(__dirname, "views");
//格式化时间
template.defaults.imports.myDateFormat = dateFormat;


//进行静态资源托管
const serve = serveStatic(path.join(__dirname, "public"));

const router = Router();
//测试路由功能(监听路由)
//进入页面直接重定向到add页面
router.get("/", (req, res) => {
    res.writeHead(301, {
        Location: "/add"
    })
    res.end();
})
router.get("/add", (req, res) => {
    let htmlStr = template("index.art", {});
    res.end(htmlStr);
})
//表单提交数据 进行post请求  路由来监听post  /add这个路由
router.post("/add", (req, res) => {
    let params = "";
    req.on("data", (results) => {
        params += results;
    })
    req.on("end", async () => {
        let data = querystring.parse(params)
        // console.log(data);
        let successData = await myInfo.create(data);
    })
    res.writeHead(301, {
        Location: "/list"
    })
    res.end();
})
//提交表单数据后重定向到list页面,并将数据通过模板引擎渲染到页面上
router.get("/list", async (req, res) => {
    let allData = await myInfo.find();
    // console.log(allData);
    let obj = {
        myAllData: allData
    }
    let htmlStr = template("list.art", obj);
    res.end(htmlStr);
})
router.get("/remove", async (req, res) => {
    let myId = url.parse(req.url, true).query.id;
    let delData = await myInfo.findOneAndDelete({
        _id: myId
    })
    // console.log(delData);
    res.writeHead(301, {
        Location: "/list"
    })
    res.end();
})
let modifyId="";
router.get("/modify", async (req, res) => {
    modifyId = url.parse(req.url, true).query.id;
    // console.log(modifyId)
    let findData = await myInfo.findOne({
        _id: modifyId
    })
    // console.log(findData);
    let htmlStr = template("index2.art", findData);
    res.end(htmlStr);
});
router.post("/modify",(req, res) => {
    let myId=mongoose.Types.ObjectId(modifyId);
    console.log(myId);
    let modifyData = "";
    req.on("data", (result) => {
        modifyData += result;
    })
    req.on("end",async() => {
        let data=querystring.parse(modifyData);
        console.log(data);
        let modifyRes=await myInfo.updateOne({
            _id: myId
        },data)
        res.writeHead(301,{
            Location:"/list"
        })
        res.end();
    })

})
//创建服务器
const app = http.createServer((req, res) => {
    /* res.writeHead(200,{
        "content-type":"text/html;charset=utf8"
    }) */
    //路由进行挂载，需要挂载到服务器上
    router(req, res, () => {//回调函数必须写，可以什么都不触发但是必须要有这个函数
        // console.log("路由器触发了");
    })

    //静态资源进行挂载，需要挂载到服务器上
    serve(req, res, () => {//回调函数必须写，可以什么都不触发但是必须要有这个函数
        // console.log("css静态资源托管");
    })
    // res.end("服务器启动成功!");
})
//服务器监听端口号8888
app.listen(8888, () => {
    console.log("http://localhost:8888");
})